package com.ydd.handler;

import com.ydd.constant.MessageConstant;
import com.ydd.exception.BaseException;
import com.ydd.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        ex.printStackTrace();
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 捕获数据库唯一约束异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result sQLIntegrityConstraintViolationExceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error("异常信息：{}", ex.getMessage());
        //唯一约束异常: Duplicate entry 'itheima' for key 'username'
        //统一返回消息: "itheima"已存在
        String[] splits = ex.getMessage().split(" ");
        //判断数组是否有数据
        if (splits != null && splits.length > 0){
            //获取下标为2的元素拼接为统一返回消息
            String msg = "[" + splits[2] + "]已存在";
            return Result.error(msg);
        }
        return Result.error(MessageConstant.UNKNOWN_ERROR);
    }
}
